<template>
  <div class="com">
    <!-- control -->
    <div>
      <span class="mr20">没有你想要的全景？请点击抓取~</span>
      <el-button type="primary" size="mini" round @click="handleMoveHouse">抓取全景</el-button>
    </div>
    <!-- list -->
    <div class="house-list" v-loading="isListloading">
      <template v-if="vrHouseList && vrHouseList.length">
        <RemarkVrListItem
          class="house-item"
          :row="item"
          v-for="item in vrHouseList"
          :key="item.id"
          @takephoto="handleTakePhoto"
        />
      </template>
      <template v-else>
        <el-result class="mt30" v-show="isShowPage" icon="success" title="该小区暂无全景，请点击上方按钮抓取">
          <template slot="icon">
            <el-image
              style="width: 200px; height: 150px;"
              :src="require('@/assets/images/port_empty@1x.png')"
            ></el-image>
          </template>
        </el-result>
      </template>
    </div>
    <!-- page -->
    <!-- <div v-if="page.total" class="d-flex jc-center mt10">
      <el-pagination
        :total="page.total"
        :page-size="page.size"
        :current-page="page.index"
        layout="prev, pager, next, total"
        @current-change="handleCurrentChange"
        background
      >
      </el-pagination>
    </div> -->
    <!-- progress -->
    <el-dialog
      class="progress-dialog"
      :visible.sync="isShowProgressDialog"
      width="600px"
      center
      append-to-body
      @close="handleCloseProgress"
      :close-on-click-modal="false"
    >
      <div class="progress">
        <el-image class="header" :src="require('@/assets/images/port_remark_progress.png')"></el-image>
        <div class="content">
          <div>
            <Progress
              v-if="isShowProgressDialog"
              :visible.sync="isShowProgressDialog"
              :state="currentMoveStatus"
              :stroke-width="20"
              type="line"
              status="exception"
              text-inside
              @done="handleMoveProgress"
            ></Progress>
          </div>
          <div class="text-center">房源信息同步中，请稍候…</div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Progress from '@/components/Progress';
import RemarkVrListItem from './RemarkVrListItem';
import { menuHandler } from '@/handler/menuHandler';
import { HOUSE_MOVE, VR_COMPOUND_ADD } from '@/config/menuId';
import { mapGetters } from 'vuex';

export default {
  name: 'RemarkVrList',

  components: {
    RemarkVrListItem,
    Progress
  },

  props: {
    houseData: {
      type: Object,
      default() {
        return {};
      }
    }
  },

  data() {
    this.MOVE_ERROR_TIPS = {
      20003: '目前不支持该网站搬家，请试试其他链接。',
      20004: '该房源已存在',
      601: '房源搬家超时，请稍后再试',
      606: '操作失败，请稍后再试',
      201: 'vr预计5分钟后下载完成'
    };
    this.currentMoveCode = '';
    this.moveTimer = null;
    this.checkTimer = null;
    return {
      isListloading: false,
      isShowPage: false,
      isShowProgressDialog: false,
      currentMoveStatus: 'P',
      // page: {
      //   total: 0,
      //   index: 1,
      //   size: 10
      // },
      vrHouseList: []
    };
  },

  computed: {
    ...mapGetters(['sessionUser'])
  },

  watch: {},

  beforeMount() {},

  mounted() {
    this.loadVrList();
  },

  beforeDestroy() {
    this.clearTimer('moveTimer');
    this.clearTimer('checkTimer');
    this.$api.cleanXFLVRFail();
  },

  methods: {
    // ------------------handle------------------
    // 改变当前页
    // handleCurrentChange(e) {
    //   this.page.index = e;
    //   this.loadVrList();
    // },
    handleTakePhoto(e) {
      this.$emit('screenshot', { type: 'id', data: e });
    },
    // 弹出搬家弹窗
    handleMoveHouse() {
      this.$prompt('复制房源链接，我们帮你抓取需要的全景图~', '上传全景', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^(((ht|f)tps?):\/\/)?[\w-]+(\.[\w-]+)+([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?$/,
        inputErrorMessage: '链接格式不正确',
        inputPlaceholder: '请复制房源链接到此处',
        closeOnClickModal: false
      })
        .then(({ value }) => {
          this.moveHouse(value);
        })
        .catch(() => {});
    },
    // 关闭搬家弹窗
    handleCloseProgress() {
      // this.page.index = 1;
      this.loadVrList();
    },
    // 搬家结束
    handleMoveProgress(e) {
      this.clearTimer('moveTimer');
      switch (e) {
        case 'timeout':
          this.$message.error(this.MOVE_ERROR_TIPS[601]);
          break;
        case 'break':
          this.$message.error(
            (this.currentMoveCode && this.MOVE_ERROR_TIPS[this.currentMoveCode]) || this.MOVE_ERROR_TIPS[606]
          );
          break;
        case 'complete':
          break;
      }
      this.currentMoveStatus = 'P';
      this.currentMoveCode = '';
    },
    // ------------------function------------------
    async moveHouse(url) {
      try {
        await Promise.all([menuHandler.call(this, HOUSE_MOVE, 1), menuHandler.call(this, VR_COMPOUND_ADD, 1)]);
        const { id, communityId } = this.houseData;
        const res = await this.$api.movingHouse([
          {
            url,
            vrFlag: true,
            skipRepeat: '1',
            xflHouseId: id,
            xflCommunityId: communityId
          }
        ]);
        // 消耗采集vr次数
        this.$api.getMemberPower({
          menuId: VR_COMPOUND_ADD,
          agentId: this.sessionUser.id,
          num: 1
        });
        // 使用搬家次数
        this.$api.getMemberPower({
          menuId: HOUSE_MOVE,
          agentId: this.sessionUser.id,
          num: 1
        });
        if (res && res.isSuccess && res.content && res.content.length) {
          this.startMoveLoop(res.content[0].id);
        } else {
          this.$message.error('非常抱歉：本次操作失败，请试试其他链接。');
        }
      } catch (error) {
        console.log('error', error);
      }
    },
    // 开始搬家轮询
    startMoveLoop(id) {
      this.clearTimer('moveTimer');
      this.isShowProgressDialog = true;
      this.moveTimer = setInterval(() => {
        this.checkHouseStatusById(id);
      }, 2500);
    },
    // 检擦搬家状态
    async checkHouseStatusById(id) {
      try {
        let res = await this.$api.taskListByIds([id]);
        let result = res.content[0];
        if (result.pickOutStatus === 'F') {
          this.currentMoveStatus = 'F';
          this.currentMoveCode = result.errorCode || '';
        }
        if (result.pickOutStatus === 'S') {
          this.currentMoveStatus = 'S';
        }
      } catch (error) {
        console.log('error', error);
      }
    },
    clearTimer(name) {
      if (this[name]) {
        clearInterval(this[name]);
        clearTimeout(this[name]);
        this[name] = null;
      }
    },
    // 获取vr下载中的id
    getPendingVrIdByStatus(status) {
      const { vrHouseList } = this;
      let filter = vrHouseList.filter((item) => {
        return item.houSubTypeState === status;
      });
      return filter.map((item) => {
        return item.delId;
      });
    },
    // 检查vr状态
    checkVrStatusChange() {
      this.clearTimer('checkTimer');
      let idList = this.getPendingVrIdByStatus('1');
      if (idList && idList.length) {
        this.checkTimer = setInterval(async () => {
          let res = await this.$api.searchDelSummaryInfo({ delIds: idList });
          if (res && res.content && res.content.length) {
            let flag = false;
            res.content.forEach((item) => {
              if (item.houSubTypeState === '1') {
                flag = true;
              }
              if (item.houSubTypeState === '10') {
                this.vrHouseList.forEach((ite, idx) => {
                  if (ite.delId === item.delId) {
                    this.$set(this.vrHouseList[idx], 'houSubTypeState', '10');
                  }
                });
              }
            });
            if (!flag) {
              this.clearTimer('checkTimer');
            }
          }
        }, 10000);
      } else {
        this.clearTimer('checkTimer');
      }
    },
    async loadVrList() {
      try {
        this.clearTimer('checkTimer');
        this.isListloading = true;
        const { communityId, communityName, hall, room, id } = this.houseData;
        // const { index, size } = this.page;
        if (!id) {
          return;
        }
        let res = await this.$api.getXFLHouseVRList({
          // page: index,
          // pageSize: size,
          communityId,
          houseId: id,
          communityName,
          hall,
          room
        });
        if (res && res.content) {
          this.vrHouseList = res.content;
          // this.page.total = res.content.total;
          this.checkVrStatusChange();
        }
      } catch (error) {
        console.log('error', error);
      } finally {
        this.isListloading = false;
        this.isShowPage = true;
      }
    }
  }
};
</script>
<style lang="scss" scoped>
@import '~@/styles/mixin.scss';
.com {
  position: relative;
}

.house-list {
  margin-top: 10px;
  height: 400px;
  overflow-y: auto;
  @include scrollBar;
}

.house-item {
  margin-top: 20px;
}

.progress-dialog {
  & /deep/ .el-dialog {
    border-radius: 16px;
  }

  & /deep/ .el-dialog__header {
    padding: 0;
  }

  & /deep/ .el-dialog__body {
    padding: 0;
  }

  & /deep/ .el-dialog__headerbtn {
    z-index: 1;
  }
}

.progress {
  position: relative;
  height: 500px;
  .header {
    width: 100%;
    height: 270px;
  }
  .content {
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    padding: 30px 50px;
    height: 230px;
    box-sizing: border-box;
  }
}

.dialog-radius /deep/ .el-dialog {
  border-radius: 16px;
}
</style>
